//// src/main/java/com/example/service/CertificateService.java
//package wsdc.app.main.v1;
//
//import jakarta.annotation.PostConstruct;
//import lombok.Getter;
//import org.bouncycastle.asn1.ASN1ObjectIdentifier;
//import org.bouncycastle.asn1.DERBitString;
//import org.bouncycastle.asn1.x500.X500Name;
//import org.bouncycastle.asn1.x500.X500NameBuilder;
//import org.bouncycastle.asn1.x500.style.BCStyle;
//import org.bouncycastle.asn1.x509.*;
//import org.bouncycastle.cert.X509CertificateHolder;
//import org.bouncycastle.cert.X509v3CertificateBuilder;
//import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
//import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;
//import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
//import org.bouncycastle.jce.provider.BouncyCastleProvider;
//import org.bouncycastle.operator.ContentSigner;
//import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
//import org.springframework.stereotype.Service;
//
//import java.io.*;
//import java.math.BigInteger;
//import java.security.*;
//import java.security.cert.Certificate;
//import java.security.cert.X509Certificate;
//import java.text.SimpleDateFormat;
//import java.util.*;
//
//@Service
//public class CertificateServiceBark {
//
//    String fileRoot = "d:\\cert\\certs";
//
//    @PostConstruct
//    public void init() {
//        Security.addProvider(new BouncyCastleProvider());
//    }
//
//    /**
//     * 生成Android 7+兼容的CA证书
//     */
//    public CertificateBundle generateAndroidCompatibleCACertificate(String commonName, String organization, String country, int validityYears) throws Exception {
//        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
//        keyPairGenerator.initialize(2048);
//        KeyPair keyPair = keyPairGenerator.generateKeyPair();
//
//        X500Name issuer = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, commonName).addRDN(BCStyle.O, organization).addRDN(BCStyle.C, country).addRDN(BCStyle.OU, "Android Compatible CA").build();
//
//        // Android建议CA证书有效期不超过10年
//        int androidValidYears = Math.min(validityYears, 10);
//        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
//        Date notBefore = new Date();
//        Date notAfter = new Date(notBefore.getTime() + androidValidYears * 365L * 24 * 60 * 60 * 1000);
//
//        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keyPair.getPublic());
//
//        // 设置基本约束扩展（CA证书）- critical
//        certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
//
//        // 设置密钥用法扩展（更完整的设置）- critical
//        certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.digitalSignature));
//
//        // 设置增强密钥用法扩展
//        certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}));
//
//        // 设置主体密钥标识符
//        JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
//        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
//
//        // 设置颁发者密钥标识符
//        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
//
//        // 添加Netscape Cert Type扩展（提高兼容性）
//        try {
//            certificateBuilder.addExtension(new ASN1ObjectIdentifier("2.16.840.1.113730.1.1"), false, new DERBitString(new byte[]{(byte) 0xC0})); // SSL CA | S/MIME CA
//        } catch (Exception e) {
//            System.out.println("Warning: Could not add Netscape Cert Type extension");
//        }
//
//        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(keyPair.getPrivate());
//
//        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
//        X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
//
//        return new CertificateBundle(certificate, keyPair.getPrivate());
//    }
//
//    /**
//     * 1. 生成CA证书
//     */
//    public CertificateBundle generateCACertificate(String commonName, String organization, String country, int validityYears) throws Exception {
//        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
//        keyPairGenerator.initialize(2048);
//        KeyPair keyPair = keyPairGenerator.generateKeyPair();
//
//        X500Name issuer = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, commonName).addRDN(BCStyle.O, organization).addRDN(BCStyle.C, country).build();
//
//        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
//        Date notBefore = new Date();
//        Date notAfter = new Date(notBefore.getTime() + validityYears * 365L * 24 * 60 * 60 * 1000);
//
//        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keyPair.getPublic());
//
//        // 设置基本约束扩展（CA证书）
//        certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
//
//        // 设置密钥用法扩展
//        certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
//
//        // 设置增强密钥用法扩展
//        certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}));
//
//        // 设置主体密钥标识符
//        JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
//        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
//
//        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(keyPair.getPrivate());
//
//        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
//        X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
//
//        return new CertificateBundle(certificate, keyPair.getPrivate());
//    }
//
//    /**
//     * 生成企业级标准CA证书（更大，更完整）
//     */
//    public CertificateBundle generateEnterpriseCACertificate(String commonName, String organization, String country, int validityYears) throws Exception {
//        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
//        keyPairGenerator.initialize(4096); // 使用4096位密钥以增加大小
//        KeyPair keyPair = keyPairGenerator.generateKeyPair();
//
//        X500Name issuer = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, commonName).addRDN(BCStyle.O, organization).addRDN(BCStyle.C, country).addRDN(BCStyle.OU, "Certificate Authority").addRDN(BCStyle.L, "Internet").addRDN(BCStyle.ST, "Server").build();
//
//        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
//        Date notBefore = new Date();
//        Date notAfter = new Date(notBefore.getTime() + validityYears * 365L * 24 * 60 * 60 * 1000);
//
//        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keyPair.getPublic());
//
//        // 设置基本约束扩展（CA证书）
//        certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
//
//        // 设置密钥用法扩展（完整设置）
//        certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.digitalSignature));
//
//        // 设置增强密钥用法扩展
//        certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_codeSigning, KeyPurposeId.id_kp_emailProtection}));
//
//        // 设置主体密钥标识符
//        JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
//        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
//
//        // 设置颁发者密钥标识符
//        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
//
//        // 添加更多扩展以增加证书大小
//        // Netscape Cert Type
//        certificateBuilder.addExtension(new ASN1ObjectIdentifier("2.16.840.1.113730.1.1"), false, new DERBitString(new byte[]{(byte) 0xC0}));
//
//        // Certificate Policies
//        PolicyInformation policyInfo = new PolicyInformation(new ASN1ObjectIdentifier("1.3.6.1.4.1.99999.1"));
//        CertificatePolicies policies = new CertificatePolicies(new PolicyInformation[]{policyInfo});
//        certificateBuilder.addExtension(Extension.certificatePolicies, false, policies);
//
//        // CRL Distribution Points
//        GeneralName crlName = new GeneralName(GeneralName.uniformResourceIdentifier, "http://ca." + commonName.toLowerCase().replace(" ", "") + "/ca-crl.crl");
//        GeneralNames crlNames = new GeneralNames(crlName);
//        DistributionPointName dpn = new DistributionPointName(crlNames);
//        DistributionPoint distPoint = new DistributionPoint(dpn, null, null);
//        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[]{distPoint}));
//
//        // Authority Information Access
//        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, "http://ocsp." + commonName.toLowerCase().replace(" ", "") + "/");
//        AccessDescription ocsp = new AccessDescription(AccessDescription.id_ad_ocsp, ocspName);
//        certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(new AccessDescription[]{ocsp}));
//
//        // Subject Alternative Name (包含CA的标识信息)
//        GeneralName sanName = new GeneralName(GeneralName.dNSName, "ca." + commonName.toLowerCase().replace(" ", ""));
//        certificateBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName[]{sanName}));
//
//        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(keyPair.getPrivate());
//
//        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
//        X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
//
//        return new CertificateBundle(certificate, keyPair.getPrivate());
//    }
//
//
//// src/main/java/wsdc/app/main/v1/CertificateService.java
//
//// ... 现有代码 ...
//
//    /**
//     * 从指定路径加载CA证书和私钥
//     */
//    public CertificateBundle loadCACertificateFromDisk(String certPath, String keyPath) throws Exception {
//        // 读取证书
//        String certContent = readPEMFile(certPath);
//        X509Certificate certificate = parseCertificate(certContent);
//
//        // 读取私钥
//        String keyContent = readPEMFile(keyPath);
//        PrivateKey privateKey = parsePrivateKey(keyContent);
//
//        return new CertificateBundle(certificate, privateKey);
//    }
//
//    /**
//     * 读取PEM文件内容
//     */
//    private String readPEMFile(String filePath) throws IOException {
//        StringBuilder content = new StringBuilder();
//        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
//            String line;
//            while ((line = reader.readLine()) != null) {
//                if (!line.startsWith("-----BEGIN") && !line.startsWith("-----END")) {
//                    content.append(line);
//                }
//            }
//        }
//        return content.toString();
//    }
//
//    /**
//     * 解析证书
//     */
//    private X509Certificate parseCertificate(String certContent) throws Exception {
//        byte[] certBytes = Base64.getDecoder().decode(certContent);
//        java.security.cert.CertificateFactory certificateFactory = java.security.cert.CertificateFactory.getInstance("X.509");
//        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(certBytes)) {
//            return (X509Certificate) certificateFactory.generateCertificate(inputStream);
//        }
//    }
//
//    /**
//     * 解析私钥
//     */
//    private PrivateKey parsePrivateKey(String keyContent) throws Exception {
//        byte[] keyBytes = Base64.getDecoder().decode(keyContent);
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//        java.security.spec.PKCS8EncodedKeySpec keySpec = new java.security.spec.PKCS8EncodedKeySpec(keyBytes);
//        return keyFactory.generatePrivate(keySpec);
//    }
//
//    /**
//     * 将证书保存为CRT格式文件
//     */
//    public void saveCertificateAsCRT(X509Certificate certificate, String filename) throws Exception {
//        File certDir = new File("d:/cert/certs");
//        if (!certDir.exists()) {
//            certDir.mkdirs();
//        }
//
//        try (FileWriter writer = new FileWriter(new File(certDir, filename))) {
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certificate.getEncoded()));
//            writer.write("\n-----END CERTIFICATE-----\n");
//        }
//    }
//
//    /**
//     * 生成OpenSSL格式的证书详情文本
//     */
//    public void saveCertificateAsOpenSSLFormat(X509Certificate certificate, String filename) throws Exception {
//        File certDir = new File(fileRoot);
//        if (!certDir.exists()) {
//            certDir.mkdirs();
//        }
//
//        try (FileWriter writer = new FileWriter(new File(certDir, filename))) {
//            // 1. PEM格式证书
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            String base64Cert = Base64.getEncoder().encodeToString(certificate.getEncoded());
//            for (int i = 0; i < base64Cert.length(); i += 64) {
//                int endIndex = Math.min(i + 64, base64Cert.length());
//                writer.write(base64Cert.substring(i, endIndex) + "\n");
//            }
//            writer.write("-----END CERTIFICATE-----\n\n");
//
//            // 2. 证书详细信息（模拟OpenSSL输出格式）
//            writer.write("Certificate:\n");
//            writer.write("    Data:\n");
//            writer.write("        Version: " + certificate.getVersion() + " (0x" + (certificate.getVersion() - 1) + ")\n");
//            writer.write("        Serial Number: " + certificate.getSerialNumber().toString(16).toUpperCase() + " (0x" + certificate.getSerialNumber().toString(16).toLowerCase() + ")\n");
//            writer.write("    Signature Algorithm: " + certificate.getSigAlgName() + "\n");
//
//            // Issuer信息
//            writer.write("        Issuer: " + certificate.getIssuerDN().toString() + "\n");
//
//            // Validity信息
//            SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm:ss yyyy z");
//            writer.write("        Validity\n");
//            writer.write("            Not Before: " + dateFormat.format(certificate.getNotBefore()) + "\n");
//            writer.write("            Not After : " + dateFormat.format(certificate.getNotAfter()) + "\n");
//
//            // Subject信息
//            writer.write("        Subject: " + certificate.getSubjectDN().toString() + "\n");
//
//            // Public Key信息
//            PublicKey publicKey = certificate.getPublicKey();
//            writer.write("        Subject Public Key Info:\n");
//            writer.write("            Public Key Algorithm: " + publicKey.getAlgorithm().toLowerCase() + "Encryption\n");
//
//            if (publicKey instanceof java.security.interfaces.RSAPublicKey) {
//                java.security.interfaces.RSAPublicKey rsaKey = (java.security.interfaces.RSAPublicKey) publicKey;
//                int keyLength = rsaKey.getModulus().bitLength();
//                writer.write("                Public-Key: (" + keyLength + " bit)\n");
//
//                // 格式化模数显示
//                String modulusHex = rsaKey.getModulus().toString(16).toUpperCase();
//                writer.write("                Modulus:\n");
//                for (int i = 0; i < modulusHex.length(); i += 30) {
//                    int endIndex = Math.min(i + 30, modulusHex.length());
//                    String hexPart = modulusHex.substring(i, endIndex);
//                    StringBuilder formattedPart = new StringBuilder();
//                    for (int j = 0; j < hexPart.length(); j += 2) {
//                        if (j > 0) formattedPart.append(":");
//                        formattedPart.append(hexPart.substring(j, Math.min(j + 2, hexPart.length())));
//                    }
//                    writer.write("                    " + formattedPart.toString() + "\n");
//                }
//                writer.write("                Exponent: " + rsaKey.getPublicExponent() + " (0x" + rsaKey.getPublicExponent().toString(16) + ")\n");
//            }
//
//            // 扩展信息
//            writer.write("        X509v3 extensions:\n");
//            try {
//                if (certificate.getBasicConstraints() >= 0) {
//                    writer.write("            X509v3 Basic Constraints: critical\n");
//                    writer.write("                CA:TRUE\n");
//                }
//
//                boolean[] keyUsage = certificate.getKeyUsage();
//                if (keyUsage != null) {
//                    writer.write("            X509v3 Key Usage: \n");
//                    List<String> usages = new ArrayList<>();
//                    if (keyUsage.length > 5 && keyUsage[5]) usages.add("Certificate Sign");
//                    if (keyUsage.length > 6 && keyUsage[6]) usages.add("CRL Sign");
//                    if (keyUsage.length > 0 && keyUsage[0]) usages.add("Digital Signature");
//                    writer.write("                " + String.join(", ", usages) + "\n");
//                }
//            } catch (Exception e) {
//                // 忽略扩展解析错误
//            }
//
//            // 签名算法
//            writer.write("\n    Signature Algorithm: " + certificate.getSigAlgName() + "\n");
//
//            // 生成指纹信息
//            writer.write("\n");
//            MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
//            byte[] sha1Fingerprint = sha1Digest.digest(certificate.getEncoded());
//            StringBuilder sha1FingerprintStr = new StringBuilder();
//            for (int i = 0; i < sha1Fingerprint.length; i++) {
//                if (i > 0) sha1FingerprintStr.append(":");
//                sha1FingerprintStr.append(String.format("%02X", sha1Fingerprint[i]));
//            }
//            writer.write("SHA1 Fingerprint=" + sha1FingerprintStr.toString() + "\n");
//
//            // SHA256指纹
//            MessageDigest sha256Digest = MessageDigest.getInstance("SHA256");
//            byte[] sha256Fingerprint = sha256Digest.digest(certificate.getEncoded());
//            StringBuilder sha256FingerprintStr = new StringBuilder();
//            for (int i = 0; i < sha256Fingerprint.length; i++) {
//                if (i > 0) sha256FingerprintStr.append(":");
//                sha256FingerprintStr.append(String.format("%02X", sha256Fingerprint[i]));
//            }
//            writer.write("SHA256 Fingerprint=" + sha256FingerprintStr.toString() + "\n");
//        }
//    }
//
//    public PKCS12Bundle loadFromPKCS12(String pkcs12Path, String password) throws Exception {
//        File pkcs12File = new File(pkcs12Path);
//        if (!pkcs12File.exists()) {
//            throw new FileNotFoundException("PKCS12文件不存在: " + pkcs12Path);
//        }
//
//        KeyStore keyStore = KeyStore.getInstance("PKCS12");
//        try (FileInputStream fis = new FileInputStream(pkcs12File)) {
//            keyStore.load(fis, password.toCharArray());
//        }
//
//        // 查找私钥条目
//        String alias = null;
//        Enumeration<String> aliases = keyStore.aliases();
//        while (aliases.hasMoreElements()) {
//            String currentAlias = aliases.nextElement();
//            if (keyStore.isKeyEntry(currentAlias)) {
//                alias = currentAlias;
//                break;
//            }
//        }
//
//        if (alias == null) {
//            throw new Exception("PKCS12文件中未找到私钥条目");
//        }
//
//        // 获取私钥
//        Key key = keyStore.getKey(alias, password.toCharArray());
//        if (!(key instanceof PrivateKey)) {
//            throw new Exception("找到的密钥不是私钥");
//        }
//        PrivateKey privateKey = (PrivateKey) key;
//
//        // 获取证书链
//        Certificate[] certChain = keyStore.getCertificateChain(alias);
//        if (certChain == null || certChain.length == 0) {
//            throw new Exception("未找到证书链");
//        }
//
//        X509Certificate certificate = (X509Certificate) certChain[0];
//        X509Certificate[] caCertificates = new X509Certificate[certChain.length - 1];
//        for (int i = 1; i < certChain.length; i++) {
//            caCertificates[i - 1] = (X509Certificate) certChain[i];
//        }
//
//        return new PKCS12Bundle(certificate, privateKey, caCertificates, alias);
//    }
//
//
//    /**
//     * PKCS12文件内容包装类
//     */
//    @Getter
//    public static class PKCS12Bundle {
//        private final X509Certificate certificate;
//        private final PrivateKey privateKey;
//        private final X509Certificate[] caCertificates;
//        private final String alias;
//
//        public PKCS12Bundle(X509Certificate certificate, PrivateKey privateKey, X509Certificate[] caCertificates, String alias) {
//            this.certificate = certificate;
//            this.privateKey = privateKey;
//            this.caCertificates = caCertificates != null ? caCertificates : new X509Certificate[0];
//            this.alias = alias;
//        }
//
//        public X509Certificate getCertificate() {
//            return certificate;
//        }
//
//        public PrivateKey getPrivateKey() {
//            return privateKey;
//        }
//
//        public X509Certificate[] getCaCertificates() {
//            return caCertificates;
//        }
//
//        public String getAlias() {
//            return alias;
//        }
//
//        public Certificate[] getCertificateChain() {
//            Certificate[] chain = new Certificate[caCertificates.length + 1];
//            chain[0] = certificate;
//            System.arraycopy(caCertificates, 0, chain, 1, caCertificates.length);
//            return chain;
//        }
//    }
//
//    /**
//     * 3. 根据CA证书生成SSL证书
//     */
//    public CertificateBundle generateSSLCertificate(CertificateBundle caBundle, String commonName, String organization, String country, String[] sanDomains, int validityYears) throws Exception {
//        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
//        keyPairGenerator.initialize(2048);
//        KeyPair keyPair = keyPairGenerator.generateKeyPair();
//
//        X509Certificate caCert = caBundle.getCertificate();
//        X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
//
//        X500Name subject = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, commonName).addRDN(BCStyle.O, organization).addRDN(BCStyle.C, country).build();
//
//        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
//        Date notBefore = new Date();
//        Date notAfter = new Date(notBefore.getTime() + validityYears * 365L * 24 * 60 * 60 * 1000);
//
//        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, keyPair.getPublic());
//
//        // 设置基本约束扩展（非CA证书）
//        certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
//
//        // 设置密钥用法扩展
//        certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
//
//        // 设置增强密钥用法扩展
//        certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}));
//
//        // 设置主体密钥标识符
//        JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
//        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
//
//        // 设置颁发者密钥标识符
//        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(caCert));
//
//        // 添加SAN扩展（Subject Alternative Name）
//        if (sanDomains != null && sanDomains.length > 0) {
//            GeneralName[] generalNames = new GeneralName[sanDomains.length];
//            for (int i = 0; i < sanDomains.length; i++) {
//                generalNames[i] = new GeneralName(GeneralName.dNSName, sanDomains[i]);
//            }
//            GeneralNames subjectAltNames = new GeneralNames(generalNames);
//            certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
//        }
//
//        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(caBundle.getPrivateKey());
//
//        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
//        X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
//
//        return new CertificateBundle(certificate, keyPair.getPrivate());
//    }
//
//    /**
//     * 生成用于Tomcat的SSL证书（PKCS12格式，包含证书和私钥）
//     */
//    public CertificateBundle generateTomcatSSLCertificate(CertificateBundle caBundle, String commonName, String organization, String country, String[] sanDomains, int validityYears, String password) throws Exception {
//        // 生成SSL证书
//        CertificateBundle sslBundle = generateSSLCertificate(caBundle, commonName, organization, country, sanDomains, validityYears);
//
//        // 保存为PKCS12格式文件（Tomcat可以直接使用）
//        saveAsPKCS12(sslBundle.getCertificate(), sslBundle.getPrivateKey(), "tomcat-ssl.p12", password);
//
//        return sslBundle;
//    }
//
//
//    /**
//     * 生成支持泛域名的Tomcat SSL证书
//     */
//    public CertificateBundle generateWildcardSSLCertificate(CertificateBundle caBundle, String commonName, String organization, String country, String[] sanDomains, String wildcardDomain, int validityYears, String password) throws Exception {
//        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
//        keyPairGenerator.initialize(2048);
//        KeyPair keyPair = keyPairGenerator.generateKeyPair();
//
//        X509Certificate caCert = caBundle.getCertificate();
//        X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
//
//        X500Name subject = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, commonName).addRDN(BCStyle.O, organization).addRDN(BCStyle.C, country).build();
//
//        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
//        Date notBefore = new Date();
//        Date notAfter = new Date(notBefore.getTime() + validityYears * 365L * 24 * 60 * 60 * 1000);
//
//        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, keyPair.getPublic());
//
//        // 设置基本约束扩展（非CA证书）
//        certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
//
//        // 设置密钥用法扩展
//        certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
//
//        // 设置增强密钥用法扩展
//        certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}));
//
//        // 设置主体密钥标识符
//        JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
//        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
//
//        // 设置颁发者密钥标识符
//        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(caCert));
//
//        // 构建SAN扩展，包含泛域名
//        List<GeneralName> generalNamesList = new ArrayList<>();
//
//        // 添加普通域名
//        if (sanDomains != null && sanDomains.length > 0) {
//            for (String domain : sanDomains) {
//                generalNamesList.add(new GeneralName(GeneralName.dNSName, domain));
//            }
//        }
//
//        // 添加泛域名（通配符域名）
//        if (wildcardDomain != null && !wildcardDomain.isEmpty()) {
//            generalNamesList.add(new GeneralName(GeneralName.dNSName, wildcardDomain));
//            // 如果泛域名不是以*开头，自动添加通配符版本
//            if (!wildcardDomain.startsWith("*.")) {
//                generalNamesList.add(new GeneralName(GeneralName.dNSName, "*." + wildcardDomain));
//            }
//        }
//
//        // 如果有SAN条目，则添加SAN扩展
//        if (!generalNamesList.isEmpty()) {
//            GeneralName[] generalNames = generalNamesList.toArray(new GeneralName[0]);
//            GeneralNames subjectAltNames = new GeneralNames(generalNames);
//            certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
//        }
//
//        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(caBundle.getPrivateKey());
//
//        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
//        X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
//
//        return new CertificateBundle(certificate, keyPair.getPrivate());
//    }
//
//    /**
//     * 将证书保存为DER格式（Android兼容格式）
//     */
//    public void saveCertificateAsDER(X509Certificate certificate, String filename) throws Exception {
//        File certDir = new File("certs");
//        if (!certDir.exists()) {
//            certDir.mkdirs();
//        }
//
//        try (FileOutputStream fos = new FileOutputStream(new File(certDir, filename))) {
//            fos.write(certificate.getEncoded());
//        }
//    }
//
//    /**
//     * 生成Android兼容的CA证书包
//     */
//    public void generateAndroidCACertificate(CertificateBundle caBundle) throws Exception {
//        X509Certificate caCert = caBundle.getCertificate();
//
//        // 保存为PEM格式（标准格式）
//        saveCertificateAsPEM(caCert, "ca-cert-android.pem");
//
//        // 保存为CRT格式（Windows兼容）
//        saveCertificateAsCRT(caCert, "ca-cert-android.crt");
//
//        // 保存为DER格式（Android二进制格式）
//        saveCertificateAsDER(caCert, "ca-cert-android.cer");
//
//        // 保存为带有扩展名的证书（某些Android版本需要.crt扩展名）
//        saveCertificateAsCRT(caCert, "ca-cert-android.cer.crt");
//
//        // 生成OpenSSL格式的详细证书信息
//        saveCertificateAsOpenSSLFormat(caCert, "ca-cert-android-openssl.txt");
//    }
//
//
//    /**
//     * 将证书保存为PEM格式文件
//     */
//    public void saveCertificateAsPEM(X509Certificate certificate, String filename) throws Exception {
//        File certDir = new File(fileRoot);
//        if (!certDir.exists()) {
//            certDir.mkdirs();
//        }
//
//        try (FileWriter writer = new FileWriter(new File(certDir, filename))) {
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certificate.getEncoded()));
//            writer.write("\n-----END CERTIFICATE-----\n");
//        }
//    }
//
//    /**
//     * 将私钥保存为PEM格式文件
//     */
//    public void savePrivateKeyAsPEM(PrivateKey privateKey, String filename) throws Exception {
//        File certDir = new File(fileRoot);
//        if (!certDir.exists()) {
//            certDir.mkdirs();
//        }
//
//        try (FileWriter writer = new FileWriter(new File(certDir, filename))) {
//            writer.write("-----BEGIN PRIVATE KEY-----\n");
//            writer.write(Base64.getEncoder().encodeToString(privateKey.getEncoded()));
//            writer.write("\n-----END PRIVATE KEY-----\n");
//        }
//    }
//
//    /**
//     * 将证书和私钥保存为PKCS12格式文件
//     */
//    public void saveAsPKCS12(X509Certificate certificate, PrivateKey privateKey, String filename, String password) throws Exception {
//        File certDir = new File(fileRoot);
//        if (!certDir.exists()) {
//            certDir.mkdirs();
//        }
//
//        KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
//        keyStore.load(null, null);
//
//        Certificate[] chain = {certificate};
//        keyStore.setKeyEntry("key", privateKey, password.toCharArray(), chain);
//
//        try (FileOutputStream fos = new FileOutputStream(new File(certDir, filename))) {
//            keyStore.store(fos, password.toCharArray());
//        }
//    }
//
//    public void saveAsPKCS12WithChain(X509Certificate certificate, PrivateKey privateKey, X509Certificate caCertificate, String filename, String password) throws Exception {
//        // 创建完整的证书链，顺序很重要：终端证书在前，CA证书在后
//        Certificate[] chain = {certificate, caCertificate};
//
//        // 创建KeyStore
//        KeyStore keyStore = KeyStore.getInstance("PKCS12");
//        keyStore.load(null, null);
//
//        // 设置密钥条目，包含完整证书链
//        keyStore.setKeyEntry("tomcat", privateKey, password.toCharArray(), chain);
//
//        // 保存到文件
//        File outputFile = new File("D:\\cert\\certs\\" + filename);
//        // 确保父目录存在
//        outputFile.getParentFile().mkdirs();
//
//        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
//            keyStore.store(fos, password.toCharArray());
//        }
//
//        //log.info("PKCS12证书保存成功: {}", outputFile.getAbsolutePath());
//    }
//
//    /**
//     * 证书和私钥的包装类
//     */
//    public static class CertificateBundle {
//        private final X509Certificate certificate;
//        private final PrivateKey privateKey;
//
//        public CertificateBundle(X509Certificate certificate, PrivateKey privateKey) {
//            this.certificate = certificate;
//            this.privateKey = privateKey;
//        }
//
//        public X509Certificate getCertificate() {
//            return certificate;
//        }
//
//        public PrivateKey getPrivateKey() {
//            return privateKey;
//        }
//    }
//
//
//    /**
//     * 生成Nginx兼容的SSL证书（PEM格式）
//     */
//    public NginxSSLCertificateBundle generateNginxSSLCertificate(CertificateBundle caBundle, String commonName, String organization, String country, String[] sanDomains, int validityYears) throws Exception {
//        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
//        keyPairGenerator.initialize(2048);
//        KeyPair keyPair = keyPairGenerator.generateKeyPair();
//
//        X509Certificate caCert = caBundle.getCertificate();
//        X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
//
//        X500Name subject = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, commonName).addRDN(BCStyle.O, organization).addRDN(BCStyle.C, country).build();
//
//        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
//        Date notBefore = new Date();
//        Date notAfter = new Date(notBefore.getTime() + validityYears * 365L * 24 * 60 * 60 * 1000);
//
//        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, keyPair.getPublic());
//
//        // 设置基本约束扩展（非CA证书）
//        certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
//
//        // 设置密钥用法扩展
//        certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
//
//        // 设置增强密钥用法扩展
//        certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}));
//
//        // 设置主体密钥标识符
//        JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
//        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
//
//        // 设置颁发者密钥标识符
//        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(caCert));
//
//        // 添加SAN扩展
//        if (sanDomains != null && sanDomains.length > 0) {
//            GeneralName[] generalNames = new GeneralName[sanDomains.length];
//            for (int i = 0; i < sanDomains.length; i++) {
//                generalNames[i] = new GeneralName(GeneralName.dNSName, sanDomains[i]);
//            }
//            GeneralNames subjectAltNames = new GeneralNames(generalNames);
//            certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
//        }
//
//        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(caBundle.getPrivateKey());
//
//        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
//        X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
//
//        return new NginxSSLCertificateBundle(certificate, keyPair.getPrivate());
//    }
//
//    /**
//     * 保存Nginx SSL证书为PEM格式
//     */
//    public void saveNginxSSLCertificate(NginxSSLCertificateBundle certBundle, String domainName) throws Exception {
//        File certDir = new File("certs/nginx/" + domainName);
//        if (!certDir.exists()) {
//            certDir.mkdirs();
//        }
//
//        // 保存服务器证书
//        try (FileWriter writer = new FileWriter(new File(certDir, domainName + ".crt"))) {
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certBundle.getCertificate().getEncoded()));
//            writer.write("\n-----END CERTIFICATE-----\n");
//        }
//
//        // 保存私钥
//        try (FileWriter writer = new FileWriter(new File(certDir, domainName + ".key"))) {
//            writer.write("-----BEGIN PRIVATE KEY-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certBundle.getPrivateKey().getEncoded()));
//            writer.write("\n-----END PRIVATE KEY-----\n");
//        }
//
//        // 保存证书链（包括CA证书）
//        try (FileWriter writer = new FileWriter(new File(certDir, domainName + "-chain.crt"))) {
//            // 服务器证书
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certBundle.getCertificate().getEncoded()));
//            writer.write("\n-----END CERTIFICATE-----\n");
//
//            // CA证书
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certBundle.getCaCertificate().getEncoded()));
//            writer.write("\n-----END CERTIFICATE-----\n");
//        }
//
//        // 保存完整的PEM文件（证书+私钥，用于某些场景）
//        try (FileWriter writer = new FileWriter(new File(certDir, domainName + "-full.pem"))) {
//            // 私钥
//            writer.write("-----BEGIN PRIVATE KEY-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certBundle.getPrivateKey().getEncoded()));
//            writer.write("\n-----END PRIVATE KEY-----\n\n");
//
//            // 服务器证书
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certBundle.getCertificate().getEncoded()));
//            writer.write("\n-----END CERTIFICATE-----\n\n");
//
//            // CA证书
//            writer.write("-----BEGIN CERTIFICATE-----\n");
//            writer.write(Base64.getEncoder().encodeToString(certBundle.getCaCertificate().getEncoded()));
//            writer.write("\n-----END CERTIFICATE-----\n");
//        }
//    }
//
//    /**
//     * Nginx SSL证书包装类
//     */
//    public static class NginxSSLCertificateBundle {
//        private final X509Certificate certificate;
//        private final PrivateKey privateKey;
//        private final X509Certificate caCertificate;
//
//        public NginxSSLCertificateBundle(X509Certificate certificate, PrivateKey privateKey) {
//            this.certificate = certificate;
//            this.privateKey = privateKey;
//            this.caCertificate = null;
//        }
//
//        public NginxSSLCertificateBundle(X509Certificate certificate, PrivateKey privateKey, X509Certificate caCertificate) {
//            this.certificate = certificate;
//            this.privateKey = privateKey;
//            this.caCertificate = caCertificate;
//        }
//
//        public X509Certificate getCertificate() {
//            return certificate;
//        }
//
//        public PrivateKey getPrivateKey() {
//            return privateKey;
//        }
//
//        public X509Certificate getCaCertificate() {
//            return caCertificate;
//        }
//    }
//
//}
